package org.imaginedays.androidall.ui;

import org.imaginedays.androidall.R;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SMSInterceptACT extends Activity {

	Button sendSMS;
	EditText phoneNo;
	EditText textMessage;
	TextView mCounter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_intercept);
		sendSMS = (Button) findViewById(R.id.sendSMS);
		phoneNo = (EditText) findViewById(R.id.phoneNo);
		textMessage = (EditText) findViewById(R.id.textMessage);
		mCounter = (TextView) findViewById(R.id.counter);
		textMessage.addTextChangedListener(mTextEditorWatcher);
		// On Click Listener on the sendSMS Button.
		sendSMS.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String mobNo = phoneNo.getText().toString();
				String message = textMessage.getText().toString();
				if (mobNo.length() > 0 && message.length() > 0)
					sendSMS(mobNo, message);
				else
					Toast.makeText(getBaseContext(),
							"Please enter both phone number and message.",
							Toast.LENGTH_SHORT).show();
			}
		});
	}

	// Method to send SMS.
	private void sendSMS(String phoneNumber, String message) {
		PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
				SMSInterceptACT.class), 0);
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, pi, null);
	}

	private final TextWatcher mTextEditorWatcher = new TextWatcher() {
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// This sets a textview to the current length
			String smsNo;
			if (s.length() == 0)
				smsNo = "0";
			else
				smsNo = String.valueOf(s.length() / 160 + 1);
			String smsLength = String.valueOf(160 - (s.length() % 160));
			mCounter.setText(smsLength + "/" + smsNo);
		}

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
		}
	};

}
